package com.cqs.leetcode.tree.segment;

import java.util.Map;
import java.util.TreeMap;

class MyCalendar {


    private final TreeMap<Integer, Integer> calender;
    private static final Map.Entry<Integer, Integer> MIN_ENTRY = new SimpleEntry(-1, -1);
    private static final Map.Entry<Integer, Integer> MAX_ENTRY = new SimpleEntry(1000000001, 1000000001);

    static class SimpleEntry implements Map.Entry<Integer, Integer> {

        private final int key, value;

        SimpleEntry(int key, int value) {
            this.key = key;
            this.value = value;
        }

        @Override
        public Integer getKey() {
            return key;
        }

        @Override
        public Integer getValue() {
            return value;
        }

        @Override
        public Integer setValue(Integer value) {
            return this.value;
        }
    }


    public MyCalendar() {
        calender = new TreeMap<>();
    }


    public boolean book(int start, int end) {
        Map.Entry<Integer, Integer> lEntry = calender.floorEntry(start);
        if (lEntry == null) lEntry = MIN_ENTRY;
        Map.Entry<Integer, Integer> rEntry = calender.ceilingEntry(lEntry.getValue());
        if (rEntry == null) rEntry = MAX_ENTRY;
        boolean succ = start >= lEntry.getValue() &&  end <= rEntry.getKey();
        if (!succ) return false;
        calender.put(start, end);
        return true;
    }
}